<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
    <title>地图显示</title>
    <style>
        html,
        body {
            height: 100%;
            margin: 0px;
            padding: 0px;
        }

        #container {
            width: 100%;
            height: 80%;
        }

        #toolControl {
            position: absolute;
            top: 10px;
            left: 0px;
            right: 0px;
            margin: auto;
            width: 252px;
            z-index: 1001;
        }

        .toolItem {
            width: 30px;
            height: 30px;
            float: left;
            margin: 1px;
            padding: 4px;
            border-radius: 3px;
            background-size: 30px 30px;
            background-position: 4px 4px;
            background-repeat: no-repeat;
            box-shadow: 0 1px 2px 0 #e4e7ef;
            background-color: #ffffff;
            border: 1px solid #ffffff;
        }

        .toolItem:hover {
            border-color: #789cff;
        }

        .active {
            border-color: #d5dff2;
            background-color: #d5dff2;
        }

        #marker {
            background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/marker_editor.png');
        }

        #polyline {
            background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/polyline.png');
        }

        #polygon {
            background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/polygon.png');
        }

        #circle {
            background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/circle.png');
        }

        #rectangle {
            background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/rectangle.png');
        }

        #ellipse {
            background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/ellipse.png');
        }
    </style>
</head>
<body onload="initMap()">
<form id="edit-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('Name')}:</label>
        <div class="col-xs-12 col-sm-8">
            <input id="c-name" class="form-control" name="row[name]" type="text" value="{$row.name}" data-rule="required">
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('Price')}:</label>
        <div class="col-xs-12 col-sm-8">
            <input id="c-price" class="form-control" step="0.01" name="row[price]" type="number" value="{$row.price}" data-rule="required">
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('Stay_time')}:</label>
        <div class="col-xs-12 col-sm-8">
            <input id="c-stay_time" class="form-control"  name="row[stay_time]" type="number" value="{$row.stay_time}" data-rule="required">
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('Status')}:</label>
        <div class="col-xs-12 col-sm-8">
            {:Form::radios('row[status]', $statuslist, $row.status, ['data-rule'=>'required'])}
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('Longitude')}:</label>
        <div class="col-xs-12 col-sm-8">
            <input id="c-longitude" class="form-control" step="0.000001" name="row[longitude]" readonly type="text" value="{$row.longitude}">
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('Latitude')}:</label>
        <div class="col-xs-12 col-sm-8">
            <input id="c-latitude" class="form-control" step="0.000001" name="row[latitude]" readonly type="text" value="{$row.latitude}">
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('地址')}:</label>
        <div class="col-xs-12 col-sm-8">
            <input id="c-address" class="form-control" name="row[address]" type="text" placeholder="">
        </div>
        <div class="col-xs-12 col-sm-2">
            <button class="btn btn-success city_address" type="button">地址定位</button>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('Area')}:</label>
        <div class="col-xs-12 col-sm-10">
            <input type="hidden" name="row[area]" id="area" value="{$row.area}">
            <div id="container"></div>
            <div>
                绘制：鼠标左键点击及移动即可绘制图形
                <br />
                结束绘制：鼠标左键双击即可结束绘制折线、多边形会自动闭合
                <br />
                中断：绘制过程中按下esc键可中断该过程
            </div>
        </div>
    </div>
    <div class="form-group layer-footer">
        <label class="control-label col-xs-12 col-sm-2"></label>
        <div class="col-xs-12 col-sm-8">
            <input type="hidden" name="row[end_edit]" value="0" id="end_edit">
            <button type="submit" class="btn btn-primary btn-embossed disabled">{:__('OK')}</button>
            <button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
        </div>
    </div>
</form>
<script charset="utf-8" src="https://map.qq.com/api/gljs?libraries=tools,service&v=1.exp&key=ABOBZ-X5AW7-RXHXD-PMSO5-COQJO-PVBD7"></script>
<script charset="utf-8" src="/assets/libs/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
    var map, editor;

    function initMap() {
        // 初始化地图
        map = new TMap.Map("container", {
            zoom: 14, // 设置地图缩放级别
            center: new TMap.LatLng({$row.latitude}, {$row.longitude}) // 设置地图中心点坐标
        });

        var paths2 = JSON.parse('<?php echo $siteArea ?>');
        var site_path = [];
        for(var j=0;j<paths2.length;j++){
            var site_j = [];
            var site_js = [];
            for(var k=0;k<paths2[j].length;k++){
                site_j.push(new TMap.LatLng(paths2[j][k][1], paths2[j][k][0]));
            }
            site_js.push(site_j);
            site_path.push(site_js);
        }


        //当前编辑区域
        var path = JSON.parse('<?php echo $area ?>');
        var new_path = [];
        for(var h=0;h<path.length;h++){
            new_path.push(new TMap.LatLng(path[h][1], path[h][0]));
        }

        var geometries = [];
        if(site_path.length != 0){
            geometries.push({
                id: 'polygonSit', // 多边形图形数据的标志信息
                styleId: 'polygon2', // 样式id
                paths: site_path, // 多边形的位置信息
                properties: {
                    // 多边形的属性数据
                    title: '区域价格',
                },
            });
        }

        // 初始化polygon
        polygon = new TMap.MultiPolygon({
            id: 'polygon-layer', // 图层id
            map: map, // 显示多边形图层的底图
            styles: {
                // 多边形的相关样式
                polygon1: new TMap.PolygonStyle({
                    color: 'rgba(46,157,222,0.3)', // 面填充色
                    showBorder: true, // 是否显示拔起面的边线
                    borderColor: '#2E9DDE', // 边线颜色
                    borderDashArray:[3,3] // 虚线数组
                }),
                polygon2: new TMap.PolygonStyle({
                    color: 'rgba(0,176,176,0.3)', // 面填充色
                    showBorder: true, // 是否显示拔起面的边线
                    borderColor: '#00B0B0', // 边线颜色
                    borderDashArray:[3,3] // 虚线数组
                }),
                polygon3: new TMap.PolygonStyle({
                    color: 'rgba(224,126,126, 0.5)', // 面填充色
                    showBorder: true, // 是否显示拔起面的边线
                    borderColor: '#F59093', // 边线颜色
                    borderDashArray:[3,3] // 虚线数组
                }),
            },
            geometries: geometries,
        });

        // 初始化几何图形及编辑器
        editor = new TMap.tools.GeometryEditor({
            map, // 编辑器绑定的地图对象
            overlayList: [ // 可编辑图层
                {
                    overlay: new TMap.MultiPolygon({
                        map,
                        styles: {
                            highlight: new TMap.PolygonStyle({
                                color: 'rgba(250,255,0,0.6)'
                            })
                        },
                        geometries: [
                            // {
                            //     paths: station_path,
                            // },
                            // {
                            //     paths: site_path,
                            // },
                            // {
                            //     paths: siteno_path,
                            // },
                            {
                                paths: new_path
                            },
                        ]
                    }),
                    id: 'polygon',
                    selectedStyleId: 'highlight'
                }
            ],

            actionMode: TMap.tools.constants.EDITOR_ACTION.INTERACT, // 编辑器的工作模式
            activeOverlayId: 'polygon', // 激活图层
            selectable: true, // 开启点选功能
            snappable: true // 开启吸附
        });

        // 监听删除、修改、拆分、合并完成事件
        let evtList = ['delete', 'adjust', 'split', 'union'];
        evtList.forEach(evtName => {
            editor.on(evtName + '_complete', evtResult => {
                var html = '';
                var positarr = [];
                for(var u=0;u<evtResult.paths.length;u++){
                    var posit = [];
                    posit.push(parseFloat(evtResult.paths[u]['lng']).toFixed(6));
                    posit.push(parseFloat(evtResult.paths[u]['lat']).toFixed(6));
                    var posith = evtResult.paths[u]['lng'].toFixed(6) + ',' + parseFloat(evtResult.paths[u]['lat']).toFixed(6);
                    positarr.push(posit);
                    if (u == evtResult.paths.length - 1){
                        html += posith;
                    }else{
                        html += posith + ";";
                    }
                }
                var center = calculateCenter(positarr);
                $("#c-longitude").val(center['lng'].toFixed(6));
                $("#c-latitude").val(center['lat'].toFixed(6));
                $("#area").val(html);
            });
        });
        // 监听拆分失败事件，获取拆分失败原因
        editor.on('split_fail', (res) => {
            alert(res.message);
        });
        // 监听合并失败事件，获取合并失败原因
        editor.on('union_fail', (res) => {
            alert(res.message);
        });

        //地址转换坐标并定位到地图
        $(".city_address").click(function (){
            var address = $("#c-address").val();
            var geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类
            geocoder.getLocation({ address: address })
                .then((result) => {
                    map.setCenter(result.result.location);
                });
        });
    }

    var calculateCenter = function (lnglatarr){
        var total = lnglatarr.length;
        var X = 0,
            Y = 0,
            Z = 0;
        lnglatarr.map((item) => {
            var lng = (item[0] * Math.PI) / 180;
            var lat = (item[1] * Math.PI) / 180;
            var x, y, z;
            x = Math.cos(lat) * Math.cos(lng);
            y = Math.cos(lat) * Math.sin(lng);
            z = Math.sin(lat);
            X += x;
            Y += y;
            Z += z;
        });
        X = X / total;
        Y = Y / total;
        Z = Z / total;
        var Lng = Math.atan2(Y, X);
        var Hyp = Math.sqrt(X * X + Y * Y);
        var Lat = Math.atan2(Z, Hyp);
        return new TMap.LatLng((Lat * 180) / Math.PI, (Lng * 180) / Math.PI);

    }
</script>
</body>
</html>